<template>
	<div class="page-follow-task">
        
        <div class="top">
			<Row :gutter="10">
				<Col :span="4">
					<Input v-model="keyWord" placeholder="输入会员卡号/姓名/手机号码" />
				</Col>
				<Col :span="4">
					<Select placeholder="全部患者类型" v-model="customerType">
						<Option v-for="item in diseaseTypeList" :value="item.id" :key="item.value">{{ item.itemValue }}</Option>
					</Select>
				</Col>
                <Col :span="16">
                    <span class="ml20">计划日期：</span>
					<DatePicker type="datetimerange" @on-change="t=>daterange=t" v-model="datetimerange" placement="top-start" placeholder="请选择随访时间范围"></DatePicker>
                    <Button class="ml20" type="primary" @click="search">查询</Button>
					<Button class="ml20" type="default" plain @click="reset">清空</Button>
                    <span><Checkbox class="check ml20">显示超时任务</Checkbox></span>
				</Col>
			</Row>
		</div>

		<Drawer class="drawer" title="执行任务" v-model="showDrawer" :width="720">
			<Form :model="editedItem" :rules="rules" :label-width="80">
			    <b class="lh200">随访信息</b>
                <Row :gutter="10">
                    <Col :span="12">
						<FormItem class="plain" label="姓名" label-position="left">
							<span>{{curCustomer.customerName}}</span>
						</FormItem>
					</Col>
					<Col :span="12">
						<FormItem class="plain" label="年龄" label-position="left">
							<span>{{curCustomer.birthday | AGE}}</span>
						</FormItem>
					</Col>
					<Col :span="12">
						<FormItem class="plain" label="性别" label-position="left">
							<span v-if="Number(curCustomer.sex)===1">男</span>
							<span v-else-if="Number(curCustomer.sex)===2">女</span>
							<span v-else>-</span>
						</FormItem>
					</Col>
					<Col :span="12">
						<FormItem class="plain" label="手机号码" label-position="left">
							<span>{{curCustomer.mobile}}</span>
						</FormItem>
					</Col>
					<Col :span="12">
						<FormItem class="plain" label="身份证号" label-position="left">
							<span>{{curCustomer.customerInfo.idCard}}</span>
						</FormItem>
					</Col>
					<Col :span="12">
						<FormItem class="plain" label="档案编号" label-position="left">
							<span>{{curCustomer.customerHealth.customerFileNumber}}</span>
						</FormItem>
					</Col>
					<Col :span="12">
						<FormItem class="plain" label="身高(cm)" label-position="left">
							<span>{{curCustomer.customerInfo.height}}</span>
						</FormItem>
					</Col>
					<Col :span="12">
						<FormItem class="plain" label="体重(kg)" label-position="left">
							<span>{{curCustomer.customerInfo.weight}}</span>
						</FormItem>
					</Col>
					<Col :span="12">
						<FormItem class="plain" label="BMI指数" label-position="left">
							<span>{{bmi}}</span>
						</FormItem>
					</Col>
					<Col :span="12">
						<FormItem class="plain" label="患者类型" label-position="left">
							<span>{{getCustomerType({customerType:curCustomer.customerInfo.diseaseType})}}</span>
						</FormItem>
					</Col>
					<Col :span="12">
						<FormItem class="plain" label="确诊时间" label-position="left">
							<span>{{curCustomer.customerInfo.careTime}}</span>
						</FormItem>
					</Col>
					<Col :span="12">
						<FormItem class="plain" label="并发症" label-position="left">
							<span>{{curCustomer.customerInfo.complication}}</span>
						</FormItem>
					</Col>
                    <Col :span="12" v-if="isFollowExecute">
						<FormItem class="plain" label="计划人员" label-position="left">
							<span>{{editedItem.planUserId}}</span>
						</FormItem>
					</Col>
                    <Col :span="12" v-if="isFollowExecute">
						<FormItem class="plain" label="计划时间" label-position="left">
							<span>{{editedItem.planTime | YMDHMS}}</span>
						</FormItem>
					</Col>
                    <Col :span="12" v-if="isFollowExecute">
						<FormItem class="plain" label="随访内容" label-position="left">
							<span>{{editedItem.followContent}}</span>
						</FormItem>
					</Col>
                </Row>
                <Divider />
			    <div v-if="isFollowExecute">
                    <b class="lh200">随访结果</b>
                    <Row type="flex" :gutter="10">
                        <Col :span="12">
                            <FormItem label="随访人员" label-position="left">
                                <Select v-model="editedItem.realUserId" class="cube" placeholder="请选择随访人员">
                                    <Option
                                        v-for="item in userList"
                                        :value="item.id"
                                        :key="item.id"
                                    >{{ item.username }}</Option>
                                </Select>
                            </FormItem>
                        </Col>
                        <Col :span="12">
                            <FormItem label="随访时间" label-position="left">
                                <DatePicker @on-change="(t1) => editedItem.realTime=t1" class="time-picker" format="" :value="editedItem.realTime" type="datetime" placeholder="请选择随访时间" />
                            </FormItem>
                        </Col>
                        <Col :span="24">
                            <FormItem label="随访结论" label-position="left" prop="followResult">
                                <Input  class="cube" type="textarea" v-model="editedItem.followResult" placeholder="" />
                            </FormItem>
                        </Col>
                    </Row>
                </div>
                <div v-if="isFollowUpdate">
                    <b class="lh200">随访信息</b>
                    <Row type="flex" :gutter="10">
                        <Col :span="12">
                            <FormItem label="计划人员" label-position="left">
                                <Select v-model="editedItem.planUserId" class="cube" placeholder="请选择计划人员">
                                    <Option
                                        class="select"
                                        v-for="item in userList"
                                        :value="item.id"
                                        :key="item.id"
                                    >{{ item.username }}</Option>
                                </Select>
                            </FormItem>
                        </Col>
                        <Col :span="12">
                            <FormItem label="随访模板" label-position="left">
                                <Select v-model="editedItem.templateId" class="cube" @on-change="templateIdChange" placeholder="请选择随访模板">
                                    <Option
                                        class="select"
                                        v-for="item in templateFollowList"
                                        :value="(item.id)"
                                        :key="item.id"
                                    >{{ item.templateName }}</Option>
                                </Select>
                            </FormItem>
                        </Col>
                        <Col :span="12">
                            <FormItem label="随访类型" label-position="left">
                                <Select v-model="editedItem.followType" class="cube" @on-change="followTypeChange" placeholder="请选择随访类型">
                                    <Option
                                        v-for="item in typeFollowList"
                                        :value="(item.id)"
                                        :key="item.id"
                                    >{{ item.itemValue }}</Option>
                                </Select>
                            </FormItem>
                        </Col>
                        <Col :span="12">
                            <FormItem label="计划时间" label-position="left">
                                <DatePicker
                                    class="time-picker"
                                    @on-change="t=>editedItem.planTime=t"
                                    :value="editedItem.planTime"
                                    type="datetime"
                                    placeholder="请选择计划时间"
                                />
                            </FormItem>
                        </Col>
                        <Col :span="24">
                            <FormItem label="随访内容" label-position="left" prop="followContent">
                                <Input class="cube" type="textarea" v-model="editedItem.followContent" placeholder />
                            </FormItem>
                        </Col>
                    </Row>
                </div>
			</Form>
			<div class="demo-drawer-footer">
				<Button style="margin-right: 8px" @click="close">取消</Button>
				<Button type="primary" @click="save" :loading="editedIndex===-1?createLoading:updateLoading">保存</Button>
			</div>
		</Drawer>
		<div>
			<div>
				<Table
					:loading="loading"
					highlight-row
					ref="currentRowTable"
					:columns="tableColumns"
					:data="items"
                    @on-selection-change="tableSelectionchange"
				>
                    <template slot-scope="{ row }" slot="createTime">
                        <span>{{row.createTime | YMDHMS}}</span>
                    </template>

                    <template slot-scope="{ row }" slot="addTime">
                        <span>{{row.addTime | YMDHMS}}</span>
                    </template>

                    <template slot-scope="{ row }" slot="followType">
                        <span>{{getFollowType(row)}}</span>
                    </template>

                    <template slot-scope="{ row }" slot="followStatus">
                        <!-- 随访状态(0.待执行，1.已执行，2执行失败，3.已取消) -->
                        <span v-if="row.followStatus===0"><i class="dot dot-orange" />待执行</span>
                        <span v-else-if="row.followStatus===1"><i class="dot dot-green" />已执行</span>
                        <span v-else-if="row.followStatus===2"><i class="dot dot-red" />执行失败</span>
                        <span v-else-if="row.followStatus===3"><i class="dot dot-gray" />已取消</span>
                        <span v-else>-</span>
                    </template>

                    <template slot-scope="{ row }" slot="birthday">
                        <span>{{row.birthday | AGE}}</span>
                    </template>
                    <template slot-scope="{ row }" slot="customerType">
                        <span>{{getDiseaseType(row.customerType)}}</span>
                    </template>
					<template slot-scope="{ row }" slot="sex">
                        <span v-if="Number(row.sex)===1">男</span>
                        <span v-else-if="Number(row.sex)===2">女</span>
                        <span v-else>-</span>
                    </template>


					<template slot-scope="{row}" slot="action">
                        <a href="javascript:;" class="mr10" @click="followExecute(row)">执行</a>
                        <a href="javascript:;" class="mr10" @click="followUpdate(row)">修改</a>
                        <a href="javascript:;" class="mr10" @click="remove(row)">取消</a>
					</template>
				</Table>
				
                <Row class="pagination">
                    <Col align="right">
                        <Page :current="page" :total="totalNum" show-total @on-change="pageChange" />
                    </Col>
                </Row>
			</div>
		</div>
	</div>
</template>
<script>
import { customerGet, customerPageQueryFollowList } from '@api/customer.js'
import { followAdd, followBatchAdd,followExecute, followUpdate ,followCancel} from '@api/follow.js'
import { mapState } from '@lib/x_.js'
export default {
	data() {
		return {
            rules: {
				interventionContent: [{ required: true, message: '请输入随访内容', trigger: 'blur' }, { type: 'string', min: 6, message: '最少6个字符', trigger: ['blur','change'] }]
            },
            bmi: '',
			showDrawer: false,
			loading: false,
			updateLoading: false,
            createLoading: false,
            editedIndex: -1,
            curCustomer: {
				birthday: '',
				customerInfo: {
					idCard: '',
					careTime: ''
                },
                customerHealth: {
                    customerFileNumber: '',
                }
			},
			editedItem: {
                templateId: '',
                followType: '',
                customerId: '',
                followContent: '',
                planTime: '',
                planUserId: '',
                realUserId: '',
                realTime: '',
                followResult: '',
			},
			defaultItem: {
                templateId: '',
                followType: '',
                customerId: '',
                followContent: '',
                planTime: '',
                planUserId: '',
                realUserId: '',
                realTime: '',
                followResult: '',
            },
            showTimePicker: false,
			items: [],
			page: 1,
			pageSize: 10,
			totalNum: 0,
			tableColumns: [
                {
					width: 60,
                    type: 'selection',
                },
                {
					width: 130,
					title: '档案编号',
					align: 'left',
					key: 'customerFileNumber',
				},
				{
					title: '姓名',
					width: 130,
					align: 'left',
					key: 'customerName',
                },
              
				{
					title: '性别',
					width: 130,
					align: 'left',
					slot: 'sex',
				},
				{
					title: '年龄',
					align: 'left',
					slot: 'birthday',
					width: 130,
				},
				{
					title: '患者类型',
					align: 'left',
					slot: 'customerType',
					width: 130,
                },
                {
					title: '随访类型',
					align: 'left',
					slot: 'followType',
					width: 130,
				},
                {
					title: '创建人',
					key: 'planUsername',
					align: 'left',
					width: 130
                },
                {
					title: '创建时间',
					slot: 'createTime',
					align: 'left',
					width: 170
                },
                {
                    title: '状态',
					slot: 'followStatus',
					width: 130,
					align: 'left',
                },
				{
					title: '操作',
					slot: 'action',
					align: 'left',
					width: 300,
					align: 'left',
                },
                {
					title: ' ',
					key: '',
					align: '',
				}
            ],
            daterange: ["",""],
            customerType: "",
            keyWord: "",
            selection: [],
            cancelReason: '',
            isFollowExecute: false,
            isFollowUpdate: false,
		}
	},
	mounted() {
        this.customerPageQueryFollowList();
	},
	computed: {
		alertTitle() {
			return this.editedIndex === -1 ? '新增' : '修改'
        },
        ...mapState(['templateFollowList','typeFollowList','diseaseTypeList','familyList','diseaseHistoryList','familyHistoryList','nowTreatmentList','tagList','userList']),
	},
	methods: {
        templateIdChange(id){
            const idx = this.templateFollowList.findIndex((item,i) => item.id === id)
            if (idx > -1) {
                const { id,templateContent,templateType } = this.templateFollowList[idx];
                const idx1 = this.typeFollowList.findIndex((item,i) => item.itemKey === templateType)
                if (idx1 > -1) {
                    const { id } = this.typeFollowList[idx1]
                    this.editedItem.followType = id;
                } else {
                    this.editedItem.followType = "";
                }
                this.editedItem.followContent = templateContent;
                this.editedItem.templateId = id;
            } else {
                this.editedItem.followContent = "";
                this.editedItem.templateId = "";
            }
        },
        followTypeChange(id){
            const idx = this.typeFollowList.findIndex((item,i) => item.id === id)
            if (idx<=-1) {
                this.editedItem.followContent = ""
                this.editedItem.templateId = "";
            }
            const { itemKey,  } = this.typeFollowList[idx]
            const idx1 = this.templateFollowList.findIndex((item,i) => item.templateType===itemKey)
            if (idx1 > -1) {
                const { templateContent,id } = this.templateFollowList[idx1]
                this.editedItem.followContent = templateContent;
                this.editedItem.templateId = id;
            } else {
                this.editedItem.followContent = ""
                this.editedItem.templateId = "";
            }
        },
        getCustomerType(row) {
			const { customerType } = row
			const { diseaseTypeList } = this
			const idx = diseaseTypeList.findIndex((item, i) => String(item.itemKey) === customerType)
			if (idx > -1) {
				return diseaseTypeList[idx]['itemValue']
			} else {
				return '-'
			}
		},
        getFollowType(row) {
            const { followType } = row;
            if (followType) {
                const idx = this.typeFollowList.findIndex((item,i) => String(item.id) === followType);
                return this.typeFollowList[idx] ? this.typeFollowList[idx]['itemValue'] : '-'
            }else {
                return '-'
            }
        },
        getDiseaseType(itemKey){
            const idx = this.diseaseTypeList.findIndex((item,i) => item.itemKey === itemKey)
            if (idx > -1) {
                return this.diseaseTypeList[idx]['itemValue']
            } else {
                return ''
            }
        },
        followExecute(row) {
            this.isFollowExecute = true;
            this.update(row)
            
        },
        followUpdate(row) {
            this.isFollowUpdate = true;
            const { customerId } = row;
            customerGet({ id: customerId }).then(res => {
				if (res.code === '0') {
					this.curCustomer = Object.assign(this.curCustomer, res.data)
				} else {
					this.modal(res, '查询患者信息')
				}
            })
            delete row.planTime
            this.update(row)
        },
        search() {
            this.page = 1;
            this.pageSize = 20;
            this.customerPageQueryFollowList();
        },
        reset() {
            this.page = 1;
            this.pageSize = 20;
            this.customerType= '';
            this.keyWord='';
            this.daterange= [];
        },
        tableSelectionchange(selection){
            selection.map((item,i) => selection[i] = item.id)
            this.selection = selection
        },
        
		pageChange(page) {
			this.page = page
			this.customerPageQueryFollowList()
		},
		update(item) {
            const { id,customerId } = item;
			this.editedIndex = item._index
			this.editedItem = Object.assign({}, item)
            this.showDrawer = true
            this.bmi = ''
            if (!customerId) {
                return;
            }
            customerGet({id: customerId}).then(res => {
                if (res.code === '0') {
                    this.curCustomer = Object.assign(this.curCustomer,res.data);
                    const { customerInfo } = this.curCustomer;
                    const { weight, height } = customerInfo || {}
                    if (weight && height) {
                        try {
                            this.bmi = Math.floor(Number(weight) /(Number(height) * Number(height)) * 10000);
                        } catch (error) {
                            
                        }
                    }
                    
                } else {
                     this.modal(res,'查询患者信息')
                }
            })
        },
		create(row) {
            this.editedIndex = -1
			this.editedItem = Object.assign({}, this.defaultItem)
			this.showDrawer = true
		},
		remove(item, idx) {
            const { id,customerName } = item;
            const that = this;
            this.$Modal.confirm({
                title:'取消随访',
                render: h => {
					return h('div', [
                        h('div',{style:'marginBottom:5px'},`确定取消患者: ${customerName} 的随访任务?`),
						h('Input', {
							props: {
                                value: this.cancelReason,
								autofocus: true,
                                placeholder: '请输入取消原因',
							},
							on: {input: val => this.cancelReason = val,}
                        })])
                },
                onOk() {
                    followCancel({id,cancelReason: that.cancelReason}).then(res => {
                        that.cancelReason = '';
                        that.modal(res,'取消随访任务');
                        that.customerPageQueryFollowList();
                    }).catch(err => that.modal(err,'取消随访任务'))
                }
            })
		},
		async save() {
            if (this.isFollowExecute) {
                const { id, realTime,realUserId, followResult } = this.editedItem;
                if (this.updateLoading) return;
                this.updateLoading = true;
                followExecute({id, realTime,realUserId, followResult }).then(res => {
                    this.modal(res,'执行随访')
                    this.updateLoading = false
                }).catch(err => {
                    this.updateLoading = false
                    this.modal(res,'执行随访')
                })
            } else if (this.isFollowUpdate) {
                if (this.createLoading) return;
                this.createLoading = true
                const { id,templateId,followType,followContent,planTime,planUserId} = this.editedItem
                if (!planTime) {
                    return this.$Message.error("请选择计划时间")
                }
                const res = await followUpdate({ id, customerId: this.curCustomer.id,templateId,followType,followContent,planTime,planUserId})
                this.createLoading = false
                this.modal(res)
            } else {
                if (this.editedIndex > -1) {
                    if (this.updateLoading) return;
                    const { id,templateId,followType,followContent,planTime,planUserId} = this.editedItem
                    if (!planTime) {
                        return this.$Message.error("请选择计划时间")
                    }
                    this.updateLoading = true;
                    const res = await followAdd({ customerId: id,templateId,followType,followContent,planTime,planUserId})
                    this.updateLoading = false
                    this.modal(res)
                } else {
                    if (this.createLoading) return;
                    const { id,templateId,followType,followContent,planTime,planUserId} = this.editedItem
                    if (!planTime) {
                        return this.$Message.error("请选择计划时间")
                    }
                    this.createLoading = true;
                    const res = await followAdd({ customerId: id,templateId,followType,followContent,planTime,planUserId})
                    this.createLoading = false
                    this.modal(res)
                }
            }
            this.customerPageQueryFollowList()
		},
		modal(res,title) {
			if (res.code === '0') {
				this.$Modal.success({
					title: title || this.alertTitle,
					content: res.data
                })
                this.close();
			} else {
				this.$Modal.warning({
					title: title || this.alertTitle,
					content: res.errMsg || '提交错误'
                })
			}
		},
		close() {
            this.showDrawer = false
            this.isFollowExecute = false;
            this.isFollowUpdate  = false;
			setTimeout(() => {
				this.editedItem = Object.assign({}, this.defaultItem)
				this.editedIndex = -1
			}, 10)
		},
        customerPageQueryFollowList() {
            this.loading || (this.loading = true)
            const { customerType,keyWord,daterange, page, pageSize, loading } = this;
            const [beginTime, endTime] = daterange;
			customerPageQueryFollowList({beginTime,endTime, customerType,keyWord,page,pageSize,status:0})
				.then(res => {
					this.loading = false
					if (res.code === '0') {
                        const { currentPage, isMore, items, pageSize, totalNum, totalPage } = res.data;
                        this.items = items;
                        this.page = currentPage;
                        this.totalNum = totalNum;
						console.log('this.items->', this.items)
					} else {
                        this.$Modal.warning({
							title: '查询列表',
							content: res.errMsg
					    })
                    }
				})
				.catch(err => {
					this.loading = false
				})
		},
	},
	watch: {
		showDrawer(after) {
			after || this.close()
        },
        typeFollowList(after){
            console.log("typeFollowList>", after)
        }
	}
}
</script>
<style lang='scss'>
.page-follow-task{
    background-color: #fff;
    .drawer{
        .ivu-select{
            width: auto;
            min-width: 250px;
        }
        .time-picker{
            min-width: 250px;
        }
        .cube{
            max-width: 600px;
        }
        .label-group {
            display: block;
        }
        .system-role {
            background-color: #fff;
        }
        .label {
            min-width: 60px;
            margin-right: 10px;
            display: inline-block;
            vertical-align: middle;
            white-space: nowrap;
            overflow: hidden;
        }
    }
}
</style>